<template>
  <el-row type="flex">
    <el-col :span="4" style="height: fit-content;">
      <el-select v-loading="groupsLoading" v-model="currentGroupId" class="bg-white group-select w-full height-50" placeholder="Select" size="large">
        <el-option
            v-for="item in groupOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.childCount === 0"
        />
      </el-select>
      <div class="child-list bg-white">
        <div class="flex-align-center pointer" :class="{'is-active' : child.id === currentChildId}" style="padding: 10px 5px;" v-for="child in children" @click="selectChildClickHandler(child.id)">
          <img :src="child.avatarUrl" style="height: 30px;width: 30px;">
          <div class="add-margin-l-5">
            {{ child.displayName }}
          </div>
        </div>
      </div>
    </el-col>
    <el-col :span="13" style="color: #323338;overflow-y: hidden;">
      <div class="notes-header bg-white">
        <div class="flex-align-justify">
          <div>
            <el-date-picker
                v-model="datetimeRange"
                type="daterange"
                range-separator="To"
                start-placeholder="Start date"
                end-placeholder="End date"
                :shortcuts="timeShortcuts"
                @change="dateChangeHandler"
                :clearable="false"
                :disabled-date="disabledDate"
            />
          </div>
          <div class="notes-active">
            <el-button type="primary" class="add-margin-l-5" @click="goRateAll">{{ $t('loc.ratAll') }}</el-button>
            <el-button type="primary" class="add-margin-l-5" @click="addNoteClickHandler">{{ $t('loc.pfRecod') }}</el-button>
          </div>
        </div>
        <div class="display-flex font-size-16 add-margin-t-10">
          <div>
            {{ $t('loc.fwk') }} : <span style="color: #10B3B7;">{{ currentChild.frameworkName }}</span>
          </div>
          <div class="add-margin-l-20">
            {{ $t('loc.activePd') }}: <span style="color: #10B3B7;">{{ activePeriodAlias.displayName }}</span>
          </div>
        </div>
      </div>

      <div class="notes-list scrollbar-new" v-loading="noteLoading">
        <note-item class="note-item" v-for="note in notes" :note="note" :childScoreRecords="childScoreRecords" :activePeriodAlias="activePeriodAlias"
                   @toFresh="loadNoteList"
        @toEdit="editNote"></note-item>
      </div>
    </el-col>
  </el-row>
  <NoteOperateDialog @needReLoadData="loadNoteList" v-model:dialogVisible="dialogNoteVisible" :child="currentChild" :note="note"></NoteOperateDialog>
</template>

<script>
import FrameworkApi from "@/api/framework";
import NoteOperateDialog from "@/views/modules/note/component/NoteOperateDialog";
import NoteItem from "@/views/modules/note/component/NoteItem";
import ChildApi from "@/api/child";
import NoteApi from "@/api/note";
import SchoolApi from "@/api/school";
import router from "@/router";
import moment from "moment";
import PeriodApi from "@/api/period";

export default {
  name: "ObservationNotes",
  components: {
    NoteOperateDialog,
    NoteItem,
  },
  data() {
    return {
      currentChildId: '',
      currentGroupId: '',
      currentSchoolId: '',
      groupOptions: [],
      groupsLoading: false,
      children: [],
      dialogNoteVisible: false,
      datetimeRange: [moment().subtract(7, 'days').format('YYYY-MM-DD'), moment()],
      childScoreRecords: [],
      timeShortcuts: [
        {
          text: 'Last week',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          },
        },
        {
          text: 'Last month',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          },
        },
        {
          text: 'Last 3 months',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          },
        },
      ],
      noteLoading: false,
      childrenLoading: false,
      notes: [],
      periodAliasList: [], // 评分周期
      note: {},
    }
  },
  watch: {
    // 時刻 监听路由
    '$route': {
      immediate: true,
      handler: function (to, oldVal) {
        // 通过路由参数获取当前的groupId childId
        this.currentSchoolId = to.params.schoolId || '';
        this.currentGroupId = to.params.groupId || '';
        this.currentChildId = to.params.childId || '';
      },
    },
    currentSchoolId: {
      immediate: true,
      handler (val, oldVal) {
        if (oldVal === val) {
          return
        }
        this.loadGroups(val);
      }
    },
    currentGroupId: {
      immediate: true,
      handler (val, oldVal) {
        if (oldVal === val) {
          return
        }
        this.loadChildren();
      }
    },
    currentChildId: {
      immediate: true,
      handler (val, oldVal) {
        if (oldVal === val) {
          return
        }
        this.loadNoteList();
        this.getChildScore(val, null ,null)
      }
    },
  },
  created() {
    this.loadPeriodAliasList()
  },
  computed: {
    currentChild() {
      console.log(this.children.find(item => item.id === this.currentChildId) || {})
      if (!this.currentChildId) {
        return this.children[0] || {}
      }
      return this.children.find(item => item.id === this.currentChildId) || {}
    },
    activePeriodAlias() {
      return this.periodAliasList.find(item => item.active === true) || {}
    },
  },
  methods: {
    dateChangeHandler() {
      this.loadNoteList()
    },
    loadGroups(schoolId) {
      if (!schoolId) {
        return
      }
      this.groupsLoading = true
      SchoolApi.getSchoolAndGroupInfo(schoolId).then(res => {
        this.groupOptions = res.groups
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.groupsLoading = false
      })
    },
    addNoteClickHandler() {
      this.dialogNoteVisible = true;
      this.note = {}
    },
    loadNoteList() {
      if (!this.currentChildId) {
        return
      }
      this.noteLoading = true
      this.datetimeRange[0] = moment(this.datetimeRange[0]).format('YYYY-MM-DD 00:00:00')
      this.datetimeRange[1] = moment(this.datetimeRange[1]).format('YYYY-MM-DD 23:59:59')
      let params = {
        childId: this.currentChildId,
        startDate: this.datetimeRange[0],
        endDate: this.datetimeRange[1],
      }
      NoteApi.getNotes(params).then(res => {
        this.notes = res
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.noteLoading = false
      })
    },
    loadChildren(groupId) {
      groupId = groupId || this.currentGroupId;
      if (!groupId) {
        return
      }
      this.childrenLoading = true
      let params = {
        groupId: groupId,
      }
      ChildApi.getChildren(params).then(res => {
        this.children = res.children.filter(child => child.isInactive !== true)
        if (this.currentChildId) {
          let child = this.children.find(item => item.id === this.currentChildId)
          if (child) {
            this.currentChildId = child.id
          } else {
            this.currentChildId = this.children[0].id
          }
        } else {
          this.currentChildId = this.children[0].id
        }
        this.updateRouter()
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.childrenLoading = false
      })
    },
    selectChildClickHandler (childId) {
      if (childId === this.currentChildId || !childId) {
        return
      }
      this.updateRouter (this.currentSchoolId, this.currentGroupId, childId)
    },
    // 更新路由
    updateRouter (schoolId, groupId, childId) {
      let params = {
        schoolId: this.currentSchoolId,
        groupId: this.currentGroupId,
        childId: this.currentChildId ? this.currentChildId : this.children[0].id
      }
      if (schoolId) {
        params.schoolId = schoolId
      }
      if (groupId) {
        params.groupId = groupId
      }
      if (childId) {
        params.childId = childId
      }
      router.push({
        name: 'note',
        params: params
      })
    },
    // 跳转到评价页面
    goRateAll () {
      let params = {
        schoolId: this.currentSchoolId,
        groupId: this.currentGroupId,
        childId: this.currentChildId
      }
      router.push({
        name: 'rateAll',
        params: params
      })
    },
    loadPeriodAliasList () {
      PeriodApi.getPeriodAlias().then(res => {
        this.periodAliasList = res
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
      })
    },
    getChildScore(childId,periodAlias,frameworkId) {
      if (!childId) {
        return
      }
      FrameworkApi.getChildScore(childId, periodAlias, frameworkId).then(res => {
        this.childScoreRecords = res
      }).catch(error => {
        this.$message.error(error.response.data.description)
      })
    },
    editNote (note) {
      this.dialogNoteVisible = true
      this.note = note
    },
    disabledDate (time) {
      return time.getTime() > Date.now()
    },
  },

}
</script>

<style scoped lang="less">
.el-row /deep/ & {
  height: 100%;
  padding: 16px 32px 0;
  gap: 15px;
  color: #303133;
  flex-wrap: nowrap;
  justify-content: center;

  & > :last-child {
    overflow-y: auto;
    padding: 0 20px;
  }
}

.group-select {
  /deep/ .el-input {
    height: 50px;
    font-size: 18px;
    color: #303133;
    background-color: #e4eaec;
  }
}
.notes-header {
  padding: 10px;

}
.child-list {
  max-height: calc(100vh - 200px);overflow: auto;
  .is-active {
    background-color: #E2F6F7;
    border-color: #e7ecee;
  }
}
.notes-list {
  margin-top: 10px;
  overflow: auto;
  height: calc(100vh - 200px);
}
.note-item {
  margin-bottom: 10px;
}
</style>